package com.yugao.fintech.antelope.auth.gituser;

import cn.hutool.http.HttpUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yugao.fintech.antelope.auth.mapper.GitUserMapper;
import com.yugao.fintech.antelope.auth.model.rqrs.third.ThirdAuthUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Objects;
@Slf4j
@Service
public class GitUserService extends ServiceImpl<GitUserMapper, GitUser> {
    private static final String OWNER = "lingyang-open";
    private static final String REPO = "draper-antelope";
    @Autowired
    private GitUserProperties properties;

    public Long saveOrUpdateUser(ThirdAuthUser authUser) {
        LambdaQueryWrapper<GitUser> lqw = GitUser.lqw().eq(GitUser::getSource, authUser.getSource())
                .eq(GitUser::getUuid, authUser.getOpenId());
        GitUser user = toUser(authUser);
        // 获取用户star状态
        user.setIsStar(isStar());

        GitUser dbUser = this.getOne(lqw);
        if (Objects.isNull(dbUser)) {
            this.save(user);
        } else {
            user.setId(dbUser.getId());
            this.updateById(user);
        }

        dbUser = this.getOne(lqw);
        return dbUser.getId();
    }

    private GitUser toUser(ThirdAuthUser authUser) {
        GitUser user = new GitUser();
        user.setSource(authUser.getSource());
        user.setUuid(authUser.getOpenId());
        user.setUsername(authUser.getUsername());
        return user;
    }

    public GitUser getUser(Long id) {
        GitUser user = this.getById(id);
        if (Objects.isNull(user)) {
            return null;
        }

        // 判断是否star
        boolean star = isStar();
        user.setIsStar(star);

        this.updateById(user);
        return user;
    }

    public boolean isStar() {
        try {
            GitUserProperties.Gitee gitee = properties.getGitee();
            String url = String.format("https://gitee.com/api/v5/user/starred/%s/%s?access_token=%s", OWNER, REPO, gitee.getAccessToken());
            String respBody = HttpUtil.get(url);
            if ("".equals(respBody)) {
                return true;
            }
            log.info("request get starred: {}, url: {}", respBody, url);
        } catch (Exception e) {
            log.error("error: ", e);
        }
        return false;
    }
}
